<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Model\UserCharge;
use App\Model\UserGrade;
use App\Model\VipFeeConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class VipController extends Controller
{
	public function index(Request $request, UserGrade $grade)
	{
		$log = $grade->select('vip_fee_config.type', 'user_grade.overed_at', 'vip_fee_config.icon_path')
			->leftJoin('vip_fee_config', 'user_grade.vip_fee_config_id', '=', 'vip_fee_config.id')
			->where('user_grade.user_id', $request->user()->id)
			->first();
		if ($log) {
			$remaining = round((strtotime($log->overed_at) - time()) / (3600 * 24));
			if ($remaining < 0) $log->type = 0;
			return $this->renderJson(['level' => $log->type, 'expire_at' => $log->overed_at, 'remaining' => $remaining, 'icon_path' => $log->icon_path]);
		}
		return $this->renderJson(['level' => 0]);
	}

	public function product()
	{
		$product = VipFeeConfig::get();

		return $this->renderJson($product);
	}

	public function pay()
	{
		$fee_id = request('fee_id');
		$vip = VipFeeConfig::find($fee_id);
		if (!$vip) {
			return $this->fail('套餐不正确');
		}
		$log = [
			'user_id' => Auth::id(),
			'money' => $vip->money,
			'expire_at' => date('Y-m-d H:i:s', strtotime('+' . $vip->days . ' day')),
			'level' => 1
		];
		UserCharge::create($log);
		return $this->success();
	}
}
